import logging
import json
import math
from util.read_excel_file import ReadExcel   # 从 util 包里导入 ReadExcel 类

logger = logging.getLogger(__name__)
class PatientInfo:

    # 读取患者信息相关(并且转成json)
    def read_patient_info_json(self):

        try:
            logger.info("开始读取患者 Excel 文件")
            reader_patient = ReadExcel('patient_info.xlsx')
            patient_data = reader_patient.load_catalog_data()

            if patient_data.empty:
                logger.warning("患者信息文件为空")
                return json.dumps({
                    "status": "warning",
                    "message": "患者信息文件为空",
                    "data": []
                }, ensure_ascii=False)

            logger.info(f"成功读取患者信息，共 {len(patient_data)} 条记录")

            # 转成字典列表
            data_list = patient_data.to_dict(orient="records")

            # 遍历每条记录，处理NaN和空值
            for record in data_list:
                for k, v in record.items():
                    # 处理浮点数NaN
                    if isinstance(v, float) and math.isnan(v):
                        record[k] = None
                    # 处理字符串'nan'和'None'
                    elif isinstance(v, str) and v.lower() in ['nan', 'none', '']:
                        record[k] = None

            # 返回 AI 友好 JSON
            return json.dumps({
                "status": "success",
                "message": f"成功读取 {len(patient_data)} 条患者信息",
                "data": data_list
            }, ensure_ascii=False)

        except Exception as e:
            logger.error(f"读取患者信息时发生错误: {str(e)}")
            return json.dumps({
                "status": "error",
                "message": f"读取患者信息时发生错误: {str(e)}",
                "data": []
            }, ensure_ascii=False)
